<template>
  <view class="content ">
    <!-- 待收货、待评价 已完成 -->
    <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>
    <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y @scroll="scrollPage" show-scrollbar="false">

      <view class="bgCart">
        <view class="cartTop">
          <view class="cartAd">
            <view class="cartAd_title">{{ navBarTitle }}</view>
          </view>
          <view class="userInfo">
            <!-- 有房子 -->
            <view class="userInfo_left" v-if="receivingAddress">
              <view class="user_address">
                <view class="user_address_text" style="max-width: 100%;"><span v-if="receivingAddress.districtName">{{  receivingAddress.districtName }}</span>{{receivingAddress.houseNumber}}</view>
                <!-- <view class="user_address_text">{{ receivingAddress.detail }}</view> -->
                <!-- 订单取消后不显示 -->
                <!-- <van-icon name="arrow" size="11" style="margin-left:10px ;" v-if="!isCancel || isSend" /> -->
              </view>
              <view class="userInfo_bottom">
                <text class="userName" style="margin-right: 10px;">{{ receivingAddress.realName }}</text>
                <text class="userTel">{{ receivingAddress.phone }}</text>
              </view>
            </view>
            <!-- 右侧按钮  自提或同城配送 -->
            <view class="userInfo_right deliveryMethod" v-if="status !== 'close' || Number(orderStatus) !==5 ">
              <view class="tab-bar gray">
                <view class="tabbar-item" v-if="shippingType == '1'"> 自提 </view>
                <view class="tabbar-item" v-if="shippingType == '2'"> 同城配送 </view>
              </view>
            </view>
          </view>
        </view>
        <!-- <view class="line" v-if="houseDataList.length>0"></view> -->
        <template>
          <!-- 自提 -->
          <view class="cart_content self-pickup" v-if="shippingType == '1'">
            <view class="self-pickup-left" @click="toSelectPick">
              <view class="self_pickup_pic"> <img
                  :src="selfPick.imgUrl ? selfPick.imgUrl : 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/zitiPic.png'"
                  alt="" mode="widthFix">
              </view>
              <view class="self_pickup_left_l">
                <view class="left_top"> <text class="self_pickup_name">{{selfPick.merchantName}}</text><text
                    class="distance">距离{{getDistanceText()}}</text>
                </view>
                <view class="left_bottom">营业时间：{{ selfPick.businessHours||'暂无营业时间' }}</view>
              </view>
            </view>
            <view class="self-pickup-right" @tap="toMap()">
              <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png" alt=""
                style="width: 16px; height: 16px;">
              <view class="spr_text">当前自提点</view>
            </view>
          </view>

          <view class="cart_content self-pickup city_delivery_content" v-if="shippingType == '2'">
            <view class="city_delivery_content_left" style="width: 85%;" v-if="status == 'unreviewed' || Number(orderStatus) == 2">
              <view class="left_top"> 订单已签收，10:32送达 </view>
              <view class="left_bottom">您的订单已签收，请核查</view>
            </view>
            <view class="city_delivery_content_left" style="width: 85%;" v-if="status == 'unreceived'|| Number(orderStatus) == 1">
              <view class="left_top"> 同城配送中，约10:32送达 </view>
              <view class="left_bottom">您的订单同城配送中</view>
            </view>
            <view class="city-delivery" style="width: 15%;">
              <view class="city_delivery_pic"> <img v-if="status == 'unreviewed' || Number(orderStatus) == 2"
                  src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/qianshou.png" alt=""
                  mode="widthFix"> </view>
              <view class="city_delivery_pic"> <img v-if="status == 'unreceived' || Number(orderStatus) == 1"
                  src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/qianshou.png" alt=""
                  mode="widthFix"> </view>
            </view>
          </view>
        </template>
        <!-- 彩色的线 -->
        <view class="clearfix">
          <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/colorLine.png" alt=""
            style=" display:block; width: 100%; height:3px;" />
        </view>

        <view class="cartList">
          <view class="goodsWraper clearfix" :class="{'goodsWraper_border':item.afterSalesStatus!==-1 }" v-for="(item, index) in ordeDetailProductInfoList" :key="index" :id="'package' + index"  >
            <!-- <view class="wraper_top">
              <view class="listTopLeft">包裹{{ item.package }}</view>
              <view class="listTopRight">{{ item.orderStatus }}</view>
            </view> -->
            <!--  -->
            <!-- v-for="(i, j) in item.goodsList" :key="index" :id="i.Id" -->
            <view class="wraper_left" @tap="toGoodsDetail(item, index)">
              <view class="productInfo_box">
                <view class="goodsPic"> <img class="img" :src="item.imgUrl" mode="widthFix" /> </view>
                <view class="goodsText">
                  <view class="goodsText_top">
                      <view class="goodsTop">
                        <view class="goods_T">{{ item.productName }}</view>
                        <view class="goods_price">X {{ item.buyNum }}</view>
                      </view>
                      <view class="googsMiddle"> <view class="goods_specs">{{ item.specName?item.specName : '默认' }}</view> </view>
                  </view>
                  <view class="goodsBottom">
                    <view class="jifen_box"><span v-if="item.productPrice && item.productPrice !== '0'"
                        style="margin-right: 16rpx;">￥{{ item.productPrice }}</span>
                      <span v-if="item.maxUsefulPoints && item.maxUsefulPoints !== '0'"><img
                          src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_gray1127.png"
                          alt="" style="height: 10px; width: 10px;margin-left: 6px;margin-right: 6px;" />
                        {{ item.maxUsefulPoints }}</span>
                    </view>
                  </view>
                </view>
              </view>
            </view>
              <view class="detailsBtnArea t28 pb30" v-if="item.afterSalesStatus !== -1 || (item.afterSalesStatus==1|| item.afterSalesStatus==2 || item.afterSalesStatus==3)" >
                <view class="btnAreaLeft"></view>
                <view class="btnAreaRight">
                  <button type="default" v-if="item.afterSalesStatus==1" plain class="blackBlackBtn" @click="toAfterSaleProcessDetail(item)">退款中</button>
                  <button type="default" v-if="item.afterSalesStatus==2" plain class="blackBlackBtn" @click="toAfterSaleProcessDetail(item)">退款成功</button>
                  <button type="default" v-if="item.afterSalesStatus==3"  plain class="blackBlackBtn" @click="toAfterSaleProcessDetail(item)">退款关闭</button>
                </view>
              </view>
          </view>
          <template v-if="Number(orderStatus)!==4">
              <view class="detailsBtnArea" v-if="status == 'unshipped' || Number(orderStatus)==0">
                <view class="btnAreaLeft"></view>
                <view class="btnAreaRight">
                  <!-- 待发货时可以修改地址 -->
                  <button type="default" plain class="blackBlackBtn r12" @click="changeAddress(1)">修改地址</button>
                  <button type="default" plain class="blackBlackBtn" @click="checkLogistics">查看物流</button>
                </view>
              </view>
              <!-- 已发货、待收货  可以看物流  与确认收货 -->
              <view class="detailsBtnArea" v-if="Number(orderStatus) == 1 || Number(orderStatus) == 10">
                <view class="btnAreaLeft"></view>
                <view class="btnAreaRight">
                  <button type="default" plain style="margin-right:10px ;" class="blackBlackBtn r12" @click="checkLogistics">查看物流</button>
                  <button type="default" plain class="blackBlackBtn" @click="openReceived">确认收货</button>
                </view>
              </view>
              <!-- 已确认收货 进入待评价 -->
              <view class="detailsBtnArea" v-if="Number(orderStatus) == 2">
                <view class="btnAreaLeft"></view>
                <view class="btnAreaRight">
                  <button type="default" plain style="margin-right:10px ;" class="blackBlackBtn r12" @click="checkLogistics()">查看物流</button>
                  <button type="default" plain class="blackBlackBtn" @click="toJudege()">去评价</button>
                </view>
              </view>
              <!-- 已完成 + 申请售后成功 -->
              <view class="detailsBtnArea" v-if="( Number(orderStatus) == 3 && (isCommentFollowups && isCommentFollowups == 1))">
                <view class="btnAreaLeft"></view>
                <view class="btnAreaRight">
                  <button type="default" plain class="blackBlackBtn" @click="toFollowUpJudege()" v-if="Number(orderStatus) == 3 && isCommentFollowups && isCommentFollowups==1">去追评</button>
                  <button type="default" plain class="blackBlackBtn" @click="checkLogistics()" v-if="Number(orderStatus) == 7">查看物流</button>
                </view>
              </view>
          </template>
        </view>
        <orderInfo :orderInfo="orderInfo" :orderStatus="orderStatus" ></orderInfo>
      </view>
    </scroll-view>
    <view class="bottom pageBottomBtnArea" v-if="Number(orderStatus) !==4" >
        <view class="service-o-icon"> 
            <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/kefu.png" alt="">
        </view>
        <view style="display: flex;justify-content: space-between; width: calc(100% - 196rpx );">
          <button type="default" plain style="margin: 0px;" class="grayBtn" @click="onApply" v-if="Number(orderStatus)!==7 && !isAllApplied">申请售后</button>
          <button type="default" plain style="margin: 0px;" class="grayBtn" @click="deleteOrder" v-else>删除订单</button>
          <button plain type="waring" class="orangeBtn" @click="addToCart">再来一单</button>
        </view>
    </view>
    <!-- 待付款 -->
    <view class="bottom bottomBtnArea pageBottomBtnArea" v-if="Number(orderStatus)==4" style="height: 144rpx;">
        <button type="default" plain style="margin: 0px; padding: 0 34rpx;" class="button" @click="cancelBtn">取消订单</button>
        <view class="checkoutBtn" :class="{ disabled: isTimeout }"  @click="toPayment">付款 <text style="margin-left: 10px;">{{ formatRemainingTime }}</text> </view>
    </view>

    <van-dialog id="van-dialog" confirm-button-color='#ff6203' />
    <applyAfterSales :show="showAfterSale" @closeApply="closeApplyPopup" :orderId="orderId"
      :orderDetailIdList="orderDetailIdList" :ordeDetailProductInfoList="ordeDetailProductInfoList"
      :sourceType="sourceType" :refundType="refundType" :afterSalesType="afterSalesType"></applyAfterSales>
    <is-shouhuo-popup :show="isShouhuo" @closeShouhuo="closeShouhuo" @confirmShouhuo="confirmShouhuo" :orderId="orderId"></is-shouhuo-popup>

  </view>
</template>

<script>
import { SOURCE_TYPE } from '@/utils/constant'
import { calculateDistance, formatDistanceText } from '@/utils/distanceUtils'  //距离计算工具
import Dialog from '@/wxcomponents/vant/dialog/dialog'
import myHouse from '@/mycomponents/myHouse.vue'
import isShouhuoPopup from '@/mycomponents/shangcheng/isShouhuoPopup.vue'
import orderInfo from '@/mycomponents/shangcheng/orderInfo.vue'
import cancelOrder from '@/mycomponents/shangcheng/cancelOrder.vue'
import applyAfterSales from '@/mycomponents/shangcheng/applyAfterSales.vue'
import {getOrderDetailApi,batchAddToShoppingCartApi,getAfterSalesOrderValidityApi,deleteOrderApi} from '@/api/order'
import { addToShoppingCartApi } from '@/api/shoppingCart'

export default {

    components: {
        isShouhuoPopup,
        myHouse,
        cancelOrder,
        applyAfterSales,
        orderInfo
    },
    name: 'Cart',
    data () {
        return {
            navBarTitle: '订单详情',
            scrolling: false, // 顶部区域吸顶效果
            showHouseName: false, // 切换房子的列表
            ebUserAddressList: [
                { // 房子列表
                    name: '水岸华庭.东郡0'
                },
                {
                    name: '水岸华庭.东郡1'
                }
            ],
            myHouse: false,
            house: 0, // 有无房屋
            showAfterSale:false,
            currentIndex: 0, // 配送方式的tab
            deliveryMethod: 'peisong',
            shippingType: '1', // 配送方式 1:自提 2:同城配送
            tabBarList: [
                {
                    name: '自提',
                    key: 'ziti'
                },
                {
                    name: '同城配送',
                    key: 'tongcheng'
                }
            ],
            userName: '王彤美',
            userTel: '15236236547',
            receivingAddress:null, //页面显示的用户地址
            businessHours: '09:00-19:00', // 营业时间
            selfPickupName: '有',
            myJifen: '6500', // 我的积分
            ordeDetailProductInfoList: [ ], // 订单商品信息
            fullDiscount:undefined, //满减活动
            coupon:undefined, //优惠券
            myCouponShow: false, // 优惠券弹窗
            paymentShow: false, // 支付方式选择弹窗
            freight: '10', // 是否显示运费 运费金额
            params: {}, // 路由传参
            isApply:false,//申请售后
            cancelPopup: false, // 取消订单
            isCancel: false, // 是否已经取消
            isPay: false, // 是否已经支付
            isSend: false, // 是否已经发货
            isReceived: false, // 已确认收货
            isJudge: false,
            payAmount: undefined, //支付金额
            payPoints: undefined, //支付使用积分
            totalAmount: undefined, // 订单总金额

            countdownText: '',
            countdown: 0,
            startTime: '',
            source:SOURCE_TYPE.ORDER, // 来源类型,
            status:'unreviewed', //订单状态
            orderStatus:'2',//订单状态-1:全部订单; 0：待发货；1：待收货；2：已收货，待评价；3：已完成；4:待付款 5: 已取消  6: 待使用
            wxUserBaseInfo:{}, //用户信息
            orderNo: '1254121144441', // 订单编号
            orderId:undefined,
            orderTime: 'undefined', // 下单时间
            orderType:undefined,// 商品类型  0=商品订单 1=服务订单
            orderDetailIdList:[],
            sourceType:'judgeOrderDetail',
            selfPick:null, //自提点信息
            productId:undefined,
            selectSuk:undefined,
            productAttrValueId:undefined,
            commentId:undefined, //追评时 需要的原评论id
            refundType:undefined, // 售后类型1=退货退款, 2=退款, 3=其他 4=服务退款
            addressId:undefined, //收货地址id
            isCommentFollowups:undefined, //是否有追评 1:有 0:没有
            canApply:false, //是否可以申请售后
            isShouhuo: false,
            orderInfo:{},//订单的部分信息   传到子组件
            afterSalesType:1, // 售后类型1=退货退款, 2=退款, 3=其他 4=服务退款
            isAllApplied:false, //是否全部售后
        }
    },

    computed: {

    },

    watch: {
      ebUserAddressList: {
            immediate: true, // 这句重要
            handler (v) {
                console.log(v, v.length, 'ebUserAddressList')
                if (v.length > 0) {
                    this.house = 0 // 有房子
                    // this.receivingAddress = v[0] // 新增：取第一个地址
                } else {
                    this.house = 1 // 没房子
                    this.selfPickupName = ''
                    this.receivingAddress = null // 清空地址显示
                }
            }
        }
    },
    onLoad (data) {
        if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(this.params,'params')
            this.source = this.params.source || SOURCE_TYPE.DEFAULT  // 设置默认来源类型
            this.status = this.params.status  //unpaid  cancel unshipped unreceived unreviewed
            this.orderStatus = this.params.orderStatus
            this.orderNo = this.params.orderNo || undefined
            this.orderId = this.params.orderId || undefined

            this.isPay = this.params.isPay || false
            this.isSend = this.params.isSend || false
            this.isReceived = this.params.isReceived || false
            this.isApply=this.params.isApply || false
            console.log(this.isApply,this.isPay, 'isPay')
            if (this.params.myHouse) {
                this.myHouse = this.params.myHouse
            }

          this.getOrderDetail(this.params.orderId)
        }

        // this.countDown();
    },

    onReady () {
        this.startCountdown()
    },
    methods: {
        // 页面左上角返回按钮
      onClickLeft() {
        console.log(this.source, 'source')
        const returnMap = {
          [SOURCE_TYPE.CART]: '/pages/shoppingCart/gouwuche',
          [SOURCE_TYPE.ORDER]: '/pages/orders/myOrder',
          [SOURCE_TYPE.PROMOTION]: '/pages/activity/promotionDetail',
          [SOURCE_TYPE.DETAIL]: '/pages/shangcheng/goodsDetail',
          [SOURCE_TYPE.DEFAULT]: '/pages/orders/myOrder',
        };
        const targetSource = this.source || SOURCE_TYPE.DEFAULT;
        const targetUrl = returnMap[targetSource] || SOURCE_TYPE.DEFAULT;

        // 清除页面栈后跳转
        uni.redirectTo({
          url: targetUrl
        });
      },
      // 滑动页面
      scrollPage (e) {
          console.log(e.detail.scrollTop, this.scrolling)
          if (e.detail.scrollTop > 25 && !this.scrolling) {
              this.scrolling = true
          } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
              this.scrolling = false
          }
      },
      // 商品详情
      toGoodsDetail(item, index) {
            const params = {}
            params.item = item
            params.id = item.productId
            params.biaozhi = 'oderDetail'
            uni.navigateTo({
              url:
                '/pages/shangcheng/goodsDetail?params=' +
                encodeURIComponent(JSON.stringify(params))
            })
        },
        // 地址选择框
        changeAddress (val) {
            console.log(val, 'val-----')
            // 交易关闭后不可修改地址
            if(Number(this.orderStatus) !== 4 && Number(this.orderStatus)  !== 0){
              return false
            }else{
              this.house = val
              this.myHouse = true
            }
        },

        closeMyHouse () {
            console.log('关闭 关闭关闭-------1111')
            this.myHouse = false
        },


        // 复制
        copytext (text) {
            var that = this
            wx.setClipboardData({
                data: text,
                success: function (res) {
                    wx.showToast({
                        title: '复制成功',
                        icon: 'success',
                        duration: 2000
                    })
                }
            })
        },
       // 修改后的距离显示方法
       getDistanceText() {
            if (!this.selfPick || !this.receivingAddress) return '距离计算中';
            try {
                const merchantLat = parseFloat(this.selfPick.latitude);
                const merchantLng = parseFloat(this.selfPick.longitude);
                const userLat = parseFloat(this.receivingAddress.latitude);
                const userLng = parseFloat(this.receivingAddress.longitude);
                
                const distance = calculateDistance(
                    merchantLat, merchantLng, 
                    userLat, userLng
                );
                
                return formatDistanceText(distance);
            } catch (e) {
                console.error('距离计算错误:', e);
                return '未知距离';
            }
        },

        // 优惠券
        openMyCoupon () {
            this.myCouponShow = true
        },
        // 关闭优惠券
        closeMyCoupon () {
            this.myCouponShow = false
        },
        // 支付方式
        openPayment () {
            this.paymentShow = true
        },
        // 关闭支付方式选择弹窗
        closePayment () {
            this.paymentShow = false
        },

        // 跳转自提点选择页面
        toSelectPick () {
          if(this.orderStatus !=='4' &&  this.orderStatus!=='0'){
            return false
          }
          const addressId = this.receivingAddress.id
            const params = {
              userAdderssDefault: this.receivingAddress,
              addressId: addressId,
              foundEleMerchant: this.selfPick,
              distance: this.getDistanceText(),
              pageSource:'orderDetails',
            }
            uni.navigateTo({
                url:
                '/pages/shoppingCart/selfPickupPoint?params=' +
                encodeURIComponent(JSON.stringify(params))
            })
        },

        // 取消订单  打开取消订单的弹窗
        cancelBtn () {
            this.cancelPopup = true
        },

        // 关闭取消订单弹窗
        closeCancelPopup (item) {
            console.log(item, 'item', typeof (item))
            this.isCancel = item
            this.cancelPopup = false

            if (item === true) {
                this.status = 'close'
                this.navBarTitle = '交易关闭'
            }
        },

        // 查看物流
        checkLogistics () {
            console.log('查看物流')
            const params = {
                orderId:this.orderId,
                orderStatus:this.orderStatus,
            }
            uni.navigateTo({
                url:
                    '/pages/orders/logisticsDetail?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },

        // 确认付款的按钮  （待付款页面） 跳转收银台
        checkoutBtn () {
            const params = {}
            uni.navigateTo({
                url: '/pages/payment/cashPage?params=' +
        encodeURIComponent(JSON.stringify(params))
            })
        },


        // 确认收货
        // submitReceived () {},
        openReceived () {
            console.log(this.orderId, 'openCheckShouhuo')
            this.isShouhuo = true
        },
        // 关闭batchInOrOutList弹窗
        closeShouhuo(){
            this.isShouhuo=false
        },
        // batchInOrOutList弹窗确认按钮
        async confirmShouhuo(item){
            this.isShouhuo=false
            console.log(item,'confirmShouhuo')
            this.getOrderDetail(this.orderId)
        },

        // 去评价
        toJudege () {
          const params ={
                source:this.source,
                orderId:this.orderId,
                orderType:this.orderType,
                productInfoList : this.ordeDetailProductInfoList
            }
          uni.navigateTo({
            url: '/pages/userJudges/sendJudge?params=' +
            encodeURIComponent(JSON.stringify(params))
          })

        },

        // 去追评
        toFollowUpJudege(item){
          const params = {
            source:this.source,
            orderId:this.orderId,
            orderType:this.orderType,
            productInfoList : this.ordeDetailProductInfoList,
            commentId:this.commentId,
          }

          uni.navigateTo({
            url: '/pages/userJudges/followUpJudge?params=' +
            encodeURIComponent(JSON.stringify(params))
          })
        },

        // 再来一单
        // addToCart(){
        //   const params = {
        //         cartId: undefined,
        //         cartNum:this.ordeDetailProductInfoList.length === 1 ?  this.ordeDetailProductInfoList[0].buyNum:1,
        //         orderId: this.params.orderId,
        //         cartType: "NORMAL",
        //         // source: SOURCE_TYPE.ORDER
        //         productId: this.productId,
        //         selectSuk : this.selectSuk, //订单中商品选择的规格  再来一单时 要选同样的规格
        //         showSpecsPopup : true,
        //         productAttrValueId:this.productAttrValueId
        //     }
        //     const addToCartParams = {
        //         cartId: undefined,
        //         cartNum: this.ordeDetailProductInfoList.length === 1 ?  this.ordeDetailProductInfoList[0].buyNum:1,
        //         cartType: "NORMAL",
        //         // combinationId: 0,
        //         productAttrValueId: this.productAttrValueId,
        //         productId: this.productId,
        //         selected: true
        //     }
        //     addToShoppingCartApi(params).then((res) => {
        //         if (res.code === 200) {
        //           wx.showToast({
        //             title: '加入购物车成功',
        //             icon: 'none',
        //             duration: 2000
        //           })
        //           uni.navigateTo({
        //             url: '/pages/shoppingCart/gouwuche?params=' +
        //               encodeURIComponent(JSON.stringify(params))
        //           })
        //         }
        //     })
        // },
      // 计入购物车   待付款订单
      async addToCart(item) {
        console.log(item, 'addToCart')
        const params = {
          orderId: item.orderId,
          showSpecsPopup: true,
        }
        const cartParams = this.ordeDetailProductInfoList.map(product => ({
          cartId: undefined,
          cartNum: product.buyNum,  // 使用每个商品自己的购买数量
          cartType: "NORMAL",
          productAttrValueId: product.productAttrValueId,
          productId: product.productId,
          selected: true
        })
        )
        console.log(cartParams, 'addToCart')
        const res = await batchAddToShoppingCartApi(cartParams)
        if (res.code == 200) {
          uni.navigateTo({
            url: '/pages/shoppingCart/gouwuche?params=' +
              encodeURIComponent(JSON.stringify(params))
          })
          wx.showToast({
            title: '加入购物车成功',
            icon: 'none',
            duration: 2000
          })
        }

      },
      // 申请售后
      onApply () {
        getAfterSalesOrderValidityApi(this.orderId).then(res=>{
          console.log(res,'getAfterSalesOrderValidityApi')
          if(res.code==200){
            this.canApply = true
            this.isAllApplied = this.ordeDetailProductInfoList.every(
              item => item.afterSalesStatus && item.afterSalesStatus !== -1 && item.afterSalesStatus!==3
            );
            if (this.isAllApplied) {
              // 抱歉，您的订单已于2015年02月10日超过售后申请时效
              Dialog.confirm({
                message: '抱歉，您订单中的商品已全部申请售后，暂无可申请商品',
                confirmButtonText: '联系客服',
                cancelButtonText: '取消',
                confirmButtonColor: '#ff6203',
                cancelButtonColor: '#888'
              }).then(() => {
                // 联系客服逻辑
                uni.makePhoneCall({
                  phoneNumber: '400-123-4567' // 替换为真实客服电话
                });
              }).catch(() => {
                // 取消操作
              });
            } else {
              // 待收货 （已签收 退货退款   未签收 退款）
              // 待评价 （退货退款）
              this.refundType = this.orderStatus == 1 ? '2' : '1'  //退款类型 1=退货退款, 2=退款,
              this.afterSalesType = this.orderStatus == 1? 2 : 1  // 售后类型1=退货退款, 2=退款, 3=其他 4=服务退款
              console.log('申请售后', this.orderStatus, this.refundType)
              this.showAfterSale = true

            }

          }else {
            this.canApply = false
             // 抱歉，您的订单已于2015年02月10日超过售后申请时效
             Dialog.confirm({
                message: '抱歉，您的订单已于'+res.data?res.data:res.message+'超过售后申请时效',
                confirmButtonText: '联系客服',
                cancelButtonText: '取消',
                confirmButtonColor: '#ff6203',
                cancelButtonColor: '#888'
              }).then(() => {
                // 联系客服逻辑
                uni.makePhoneCall({
                  phoneNumber: '400-123-4567' // 替换为真实客服电话
                });
              }).catch(() => {
              });
          }
        }).catch(err => {
          console.error('申请售后验证失败:', err)
          this.canApply = false
        })
      },
      // 跳转申请售后详情页面  关闭弹窗
      closeApplyPopup(){
          this.showAfterSale=false
      },
      // 删除订单
      deleteOrder(){
        Dialog.confirm({
          message: '确认删除记录'
        }).then(() => {
          deleteOrderApi(this.orderId).then(res => {
            if (res.code == 200) {
              this.getOrderDetail()
            }
          })
        })
          .catch(() => {
            console.log('cancel')
          })
      },
    

        // 退款成功
        toAfterSaleProcessDetail(item){
          const params = {
            orderId:this.orderId,
            orderStatus:this.orderStatus,
            afterSalesId:item.afterSalesId,
            afterSalesType:this.orderStatus ==1 ? 2 :1
          }
          uni.navigateTo({
            url: '/pages/orders/refundOrderDetail?params=' +
            encodeURIComponent(JSON.stringify(params))
          })
        },




        // 跳转自提点
        toMap(){
            console.log(this.selfPick,'this.selfPick')
            const params = {
              merchantLocation: {
                latitude: this.selfPick.latitude,
                longitude: this.selfPick.longitude
              },
              userLocation:{
                latitude: this.receivingAddress.latitude,
                longitude: this.receivingAddress.longitude
              }
            }
            uni.navigateTo({
                url:
                '/pages/shoppingCart/map?params=' +
                encodeURIComponent(JSON.stringify(params))
            })
        },
        // 开始倒计时的函数
        startCountdown () {
            // 获取当前时间作为开始时间（这里可以根据你的实际需求设置具体的开始时间，比如从服务器获取指定的开始时间等）

            this.startTime = new Date()
            console.log(this.startTime, 'startTime')
            // 设置倒计时总时长为30分钟，换算成毫秒
            const totalSeconds = 30 * 60
            this.countdown = totalSeconds

            // 启动倒计时定时器
            this.countdownTimer = setInterval(() => {
                const currentTime = new Date()
                const elapsedSeconds = Math.floor((currentTime - this.startTime) / 1000)
                const remainingSeconds = this.countdown - elapsedSeconds

                if (remainingSeconds <= 0) {
                    // 倒计时结束，清除定时器
                    clearInterval(this.countdownTimer)
                    this.setData({
                        countdownText: '倒计时结束'
                    })
                } else {
                    // 格式化剩余时间为分钟和秒的格式，并更新到界面显示
                    const minutes = Math.floor(remainingSeconds / 60)
                    const seconds = remainingSeconds % 60
                    const countdownText = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
                    this.countdownText = countdownText
                }
            }, 1000)
        },
         /**
         * 接口
         */
        // 获取订单详情
        getOrderDetail (orderId) {
            getOrderDetailApi(orderId).then(res => {
                console.log(res, '订单详情')
                if(res.code == 200){
                  this.ordeDetailProductInfoList = res?.data?.ordeDetailProductInfoList || []
                  this.orderDetailIdList = this.ordeDetailProductInfoList.map(item => item.orderDetailId)
                  this.productId = this.ordeDetailProductInfoList[0]?.productId || undefined  //再来一单按钮需要用到
                  this.selectSuk = this.ordeDetailProductInfoList[0]?.specName || undefined  //再来一单按钮需要用到
                  this.productAttrValueId = this.ordeDetailProductInfoList[0]?.productAttrValueId || undefined  //再来一单按钮需要用到
                  this.freight = res?.data?.freight || 0
                  this.orderNo = res.data.orderNo  || undefined
                  this.orderTime = res.data.orderTime  || undefined
                  this.payPoints = res.data.payPoints  || '0'
                  this.payAmount = res.data.payAmount  || '0'
                  this.totalAmount = res.data.totalAmount || '0'
                  this.fullDiscount = res.data.fullDiscount || undefined //满减活动
                  this.coupon = res.data.coupon || undefined //优惠券
                  const shippingType = res.data.shippingType
                  this.shippingType = shippingType || '1'
                  // this.deliveryMethod = shippingType == 1 ? 'ziti' : 'tongcheng'
                  // console.log(this.deliveryMethod, 'deliveryMethod')
                  this.orderStatus = res.data?.orderStatus || undefined //订单状态-1:全部订单; 0：待发货；1：待收货；2：已收货，待评价；3：已完成；4:待付款 5: 已取消  6: 待使用 7:已关闭
                  this.wxUserBaseInfo = res.data?.wxUserBaseInfoResponse || {}
                  this.ebUserAddressList = this.wxUserBaseInfo?.ebUserAddressList || []
                  this.addressId = res.data.addressId // 新增：更新addressId
                  // 新增：根据addressId设置receivingAddress
                  this.receivingAddress = this.ebUserAddressList.find(item => item.id == this.addressId)
                 
                  this.selfPick = res.data?.selfPick || null
                  this.orderType = res.data.orderType || 0 //商品类型
                  this.isCommentFollowups = res.data?.isCommentFollowups || undefined //是否有追评
                  this.commentId = res.data?.commentId || undefined //评价id
                  this.orderInfo= {
                    orderId: res.data.orderId,
                    orderNo: res.data.orderNo,
                    orderTime: res.data.orderTime,
                    payPoints: res.data.payPoints || 0,
                    payAmount: res.data.payAmount || 0,
                    totalAmount: res?.data?.totalAmount || 0,
                    fullDiscount: res.data?.fullDiscount || undefined,
                    coupon: res?.data?.coupon|| undefined,
                    shippingType: res?.data?.shippingType || '1',
                    orderStatus: res.data.orderStatus,
                    wxUserBaseInfo: res.data.wxUserBaseInfoResponse,
                    freight:res?.data?.freight || 0,
                    orderType: res.data.orderType

                  }
                  // 是否已经全部申请售后  且售后未关闭
                  this.isAllApplied = this.ordeDetailProductInfoList.every(
                    item => item.afterSalesStatus && item.afterSalesStatus !== -1 && item.afterSalesStatus !== 3
                  );
                }
            })
        },


    }

}
</script>
  <style lang="scss" scoped>
  // @import '@/styles/variables.scss';

  .content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background-color: #FFFFFF;
  }

  .bgCart {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: #f9f9f9;
    // height: 100vh;
  }

  // 滚动
  .scroll-content {
    flex: 1;
    height: 1px;
  }

  .cartTop {
    background-color: #ffffff;
    padding-left: 24px;
    padding-right: 24px;
    padding-top: 25px;

    // 页面标题部分
    .cartAd {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .cartAd_title {
      font-size: 60rpx;
      text-align: left;
      line-height: 60rpx;
      color: #111111;
    }

    .userInfo {
      margin-top: 25px;
      display: flex;
      justify-content: space-between;
      padding-bottom: 23px;

    }

    .userInfo_left {
      //左边用户信息
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 75%;
    }

    .user_address { //住址
      font-size: 28rpx;
      text-align: left;
      color: #737373;
      width: 100%;
      display: flex;
      align-items: center;
    }
    .user_address_text{
      max-width: 75%;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 超出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }

    .userInfo_bottom {
      // font-weight: bolder;
      font-size: 28rpx;
      text-align: left;
      color: #737373;
      line-height: 28rpx;
      margin-top: 13px;

    }

    .userInfo_right {
      float: right;
      text-align: right;
    }

  }

  // 配送方方式
  .tab-bar {
    padding: 0px 2px;
    height: 20px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  // 日月周统计

  //自提  同城配送
  .gray {
    height: 20px;

    .tabbar-item {
      z-index: 1;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
      font-size: 24rpx;
      background: #FF6203;
      border-radius: 10px;
      padding: 0px 12px;
      color: #ffffff;
    }
  }

  // 标题下面的横线
  .line {
    height: 9px;
    width: 100%;
    background: #f9f9f9;
  }

  // 自提点
  .self-pickup {
    margin-top: 10px;
    padding: 24px;
    background-color: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  // 有自提点的内容
  .self-pickup-left {
    width: 75%;
    display: flex;

    .self_pickup_pic {
      width: 20%;
      display: flex;
      flex-direction: column;
      text-align: center;
      justify-content: center;

      img {
        width: 100%;
        height: auto;
      }
    }

    // 图片右边的文字
    .self_pickup_left_l {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      width: 70%;
      margin-left: 15px;

      .left_top {
        font-size: 22rpx;
        text-align: left;

        .self_pickup_name {
          color: #737373;
          margin-right: 7px;
        }

        .distance {
          color: #FF6203;
        }
      }

      .left_bottom {
        font-size: 22rpx;
        text-align: left;
        color: #737373;
      }
    }

  }

  .self-pickup-right {
    display: flex;

    .spr_text {
      margin-left: 8px;
      font-size: 22rpx;
      text-align: left;
      color: #888888;
    }
  }

//   同城配送
.city_delivery_content {
    display: flex;
    align-items: center;

    .city_delivery_content_left {
        width: 85%;
        display: flex;
        justify-content: space-between;
        flex-direction: column;

        .left_top {
            // flex: auto;
            font-size: 28rpx;
            text-align: left;
        }

        .left_bottom {
            font-size: 22rpx;
            text-align: left;
            color: #737373;
        }
    }

    .city-delivery {
        width: 15%;
        .city_delivery_pic {
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;

            img {
                width: 100%;
                height: auto;
            }
        }
    }
}

  // 无自提点
  .no-self-pickup {
    font-weight: bolder;
    font-size: 28rpx;
    text-align: left;
    color: #FF6203;
  }

  .cartList {
    padding: 48rpx;
    width: calc(100% - 96rpx);
    background-color: #ffffff;
    // border-bottom: 1rpx solid #f0f0f0;
  }

  .goodsWraper {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin-bottom: 30rpx;
  }

  .goodsWraper:last-child {
    margin-bottom: 0px;
    border-bottom: none;
  }
  .goodsWraper_border{
    border-bottom: 1px solid #e5e5e5;
  }

  .wraper_top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;

    .listTopLeft{
        color: #737373;
        font-size: 28rpx;
        line-height: 28rpx;
    }
    .listTopRight{
        color: #FF6203 ;
        font-size: 24rpx;
        line-height: 24rpx;
    }
  }

.wraper_left {
  width: 100%;
  // margin-bottom: 30rpx;  //多个商品时 每个商品之间的间距

  .productInfo_box{
    display: flex;
    width: 100%;
  }

  .goodsPic {
    width: 33%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    img {
      width: 100%;
      height: auto;
    }
  }

  .goodsText {
    position: relative;
    width: 67%;
    margin-left: 14px;
    // width: 150px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-top: 12rpx;
    padding-bottom: 20rpx;
    text-align: left;

    .goodsTop {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .goods_T {
        font-size: 28rpx;
        text-align: left;
        color: #111111;
        max-width: 80%;
        line-height: 28rpx;
        // margin-top: 9px;  //display：flex   中 元素居中
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 超出部分隐藏 */
        text-overflow: ellipsis;
        /* 显示省略号 */

      }

      // 商品价格
      .goods_price {
        font-size: 28rpx;
        color: #737373;
        line-height:28rpx;
      }
    }

    .googsMiddle {
      // position: absolute;
      // top: 25%;
      margin-top: 24rpx;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 22rpx;
      color: #666666;

      .goods_specs {
        // margin-top: 7px;
        max-width: 80%;
        font-size: 22rpx;
        text-align: left;
        color: #666666;
        //   line-height: 11px;

        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
      }

      .goods_num {
        font-size: 22rpx;
        line-height: 22rpx;
        color: #666666;
      }

    }

    .goodsBottom {
      // position: absolute;
      // top: 77%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      //   max-width: 90%;
      // margin-top: 30px;

      .money {
        font-size: 28rpx;
        text-align: left;
        color: #737373;
        line-height: 28rpx;
        // margin-right: 21px;
      }

      .jifen_box {
        font-size: 28rpx;
        text-align: left;
        color: #999999;
        line-height: 28rpx;
        height: 28rpx;
      }
    }
  }
}
.wraper_left:last-child{
  margin-bottom: 0px;
}


// 页面所有按钮
// 商品或服务下方的的按钮区域
.detailsBtnArea {
    // margin-top: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 62rpx;
    // padding-top: 14px;
    // padding-bottom: 14px;

    .btnAreaLeft {
        color: #888888;
        font-size: 22rpx;
        line-height: 22rpx;
        width: 20rpx;
    }
    .btnAreaRight {
        display: flex;
        justify-content: space-between;
    }

}
// 黑字黑框按钮
.blackBlackBtn {
    background-color: #Ffffff;
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #111111;
    height: 60rpx;
    line-height: 58rpx;
    border: 1rpx solid #111111;
    padding-left: 10px;
    padding-right: 10px;
    min-width: 162rpx;
}
// 已付款的其他状态按钮区域
.pageBottomBtnArea{
  padding-top: 48rpx;
  padding-bottom: calc(48rpx + env(safe-area-inset-bottom));
  background: #ffffff; 
  display: flex;
  align-items: center;
  justify-content: space-between;
}
  // 未付款页面底部的按钮
  .bottomBtnArea {
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #f9f9f9;
    background-color: #ffffff;
    padding-bottom: 20px;
    padding-left: 24px;
    padding-right: 24px;
    width: calc(100% - 48px);
  }
  // 付款按钮
  .checkoutBtn {
    background-color: #FF6203;
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #FFFFFF;
    height: 62rpx;
    line-height: 60rpx;
    padding-left: 50px;
    padding-right: 50px;
  }

  .button {
    background-color: #Ffffff;
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #111111;
    height: 62rpx;
    line-height: 60rpx;
    border: 1px solid #D4D4D4 !important;
    padding-left: 10px;
    padding-right: 10px;
    margin-right: 12px;
    // padding-left: 13px;
    // padding-right: 13px;
    // margin-right: 15px;
  }

  .checkBtn {
    border: 1px solid #FF6203 !important;
    background-color: transparent;
    /* width: 100%; */
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #FF6203 !important;
    height: 62rpx;
    line-height: 60rpx;
    padding-left: 13px;
    padding-right: 13px;
  }

  button {
    border: none;
  }

.bottom{
  border-top: 1px solid #f9f9f9;
}


//   button[plain]{
//     border: none;
// }

.grayBtn{
    background-color: #Ffffff;
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #111111;
    height: 62rpx;
    line-height: 60rpx;
    border: 1px solid #D4D4D4 !important;
    // padding-left: 17px;
    // padding-right: 17px;
    width: 45%;
  }
.orangeBtn {
    background-color: #FF6203;
    border: none;
    border-radius: 38px;
    font-size: 28rpx;
    text-align: center;
    color: #FFFFFF;
    height: 62rpx;
    line-height: 60rpx;
    // padding-left: 17px;
    // padding-right: 17px;
    width: 45%;
}
.orangeBtn button[plain]{
  border:none
}

//防止父元素高度塌陷
.clearfix::before .clearfix::after {
  content: "";
  display: table;
  clear: both;
}

.line_two {
  height: 5px;
  width: 100%;
  background: #f9f9f9;
  line-height: 5px;
}

// 价格明细
.price_detail {
  padding: 24px 24px 108px 24px;
  background-color: #ffffff;
  margin-top: 10px;

  .price_detail_content {
    border-bottom: 2rpx solid #f9f9f9;
    padding-bottom: 20px;
  }

  .price_detail_title {
    font-size: 40rpx;
    text-align: left;
    color: #111111;
  }

  .price_detail_box {
    margin-top: 17px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .num {
    font-size: 28rpx;
    text-align: right;
    color: #111111;
  }

  .num_o {
    font-size: 28rpx;
    text-align: right;
    color: #FF6203;
  }

  // 实付金额
  .payment {
    padding: 24px 0px;

  }

}

// 很多地方字体 颜色公用
.price_detail_name {
  font-size: 28rpx;
  line-height: 28rpx;
  text-align: left;
  color: #111111;
}

.price_detail_tips {
  font-size: 24rpx;
  text-align: left;
  color: #666666;
  margin-top: 5px;
}

.checked-img {
  height: 16px;
  width: 16px;
}

.payment_top {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .paidAmount {
    font-size: 32rpx;
    color: #111111;
    line-height: 32rpx;
  }
}

.order_Detail {
  padding-bottom: 100px;
}

// 订单编号
.order_Detail_box {
  margin-top: 17px;
  display: flex;
  align-items: center;
  justify-content: space-between;

}

.order_detail_num {
  display: flex;
  align-items: center;
}

.code {
  font-size: 24rpx;
  text-align: right;
  color: #888888;
  line-height: 24rpx;
}

.copy {
  font-size: 24rpx;
  text-align: right;
  color: #111111;
  line-height: 24rpx;
}
.service-o-icon{
  width: 96rpx;
  height: 62rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  img{
    width: 45rpx;
		height: 45rpx;
  }
}

::v-deep .service-o-icon .van-icon{
  font-size:44rpx!important;
  color: #000000!important;
}
::v-deep .van-nav-bar__left {
  width: 56px;
  height: 44px;
}

::v-deep .van-icon {
  color: #242629 !important;
}

// ::v-deep .van-icon::before {
//   content: "";
//   display: block;
//   width: 24px;
//   background-size: 24px;
//   height: 24px;
// }
::v-deep .van-nav-bar__title {
  font-size: 28rpx;
  color: #333333;
}

// ::v-deep .bar-class, .van-submit-bar__bar{
//   display: flex;
//   justify-content: space-between !important;
// }

::v-deep .van-button--warning {
  background-color: #FF6203;
}

::v-deep .van-icon-success {
  color: #ffffff !important;
}

::v-deep .van-submit-bar__bar {
  display: flex;
  justify-content: space-between !important;
  border-top: 1px solid #f9f9f9;
  padding-top: 32rpx !important;
}

::v-deep .disabledSubmit .van-button--danger,
.van-button--disabled,
.van-button--unclickable {
  background-color: #D4D4D4 !important;
  border: 1px solid #D4D4D4 !important;
}
// 组件 底部的线
::v-deep .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}
// ::v-deep
// 向右的箭头
.van-icon-arrow {
  color: #666666 !important;
}
.r12{
  margin-right: 12px;
}
.t28{
  margin-top: 28rpx;
}
.pb30{
  padding-bottom: 30rpx;
}
::v-deep .van-button--primary {
  width: 100% !important;
  border-radius: 50rpx;
}
</style>
